package com.zxj.geekstudy.controller;

import com.zxj.geekstudy.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
@Slf4j
public class UserController {

    @Resource
    private RedisUtil redisUtil;

    /**
     * 分布式锁测试
     * @return
     */
    @RequestMapping("testLock")
    public String testLock() {
        String key = "testLock";
        String val = UUID.randomUUID().toString();
        boolean lock = redisUtil.lock(key, val, 60, TimeUnit.SECONDS);
        if (lock) {
            log.info("redis分布式锁加锁成功, key:{}, val:{}", key, val);
        }
        boolean unlock = redisUtil.unlock(key, val);
        if (unlock) {
            log.info("redis分布式锁解锁成功, key:{}, val:{}", key, val);
        }
        return "success";
    }

    /**
     * 分布式计数器-创建库存
     * @return
     */
    @RequestMapping("testSetGoods")
    public String testSetGoods() {
        String key = "testGoods";
        redisUtil.set(key, 10, 60, TimeUnit.MINUTES);
        log.info("redis测试分布式计数器，模拟减库存，key:{}, result:{}", key);
        return "success";
    }

    /**
     * 分布式计数器-模拟减库存
     * @return
     */
    @RequestMapping("testDecrementGoods")
    public String testDecrementGoods() {
        String key = "testGoods";
        boolean result = redisUtil.decrementGoods(key);
        log.info("redis测试分布式计数器，模拟减库存，key:{}, result:{}", key, result);
        return "success";
    }

    /**
     * PubSub 实现订单异步处理
     * @return
     */
    @RequestMapping("testPubSub")
    public String testPubSub() {
        String channel = "pubSubTest";
        String val = UUID.randomUUID().toString();
        redisUtil.publish(channel, val);
        log.info("redis测试PubSub，channel:{}, val:{}", channel, val);
        return "success";
    }
}
